package com.motong.gongdan.controller.system;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.motong.gongdan.config.CustomCellWriteHandler;
import com.motong.gongdan.config.ResponseData;
import com.motong.gongdan.config.auth.UserLoginToken;
import com.motong.gongdan.constant.CommonConstant;
import com.motong.gongdan.entity.ExceptionNotice;
import com.motong.gongdan.entity.ExceptionType;
import com.motong.gongdan.entity.User;
import com.motong.gongdan.service.ExceptionInfoService;
import com.motong.gongdan.service.ExceptionNoticeService;
import com.motong.gongdan.service.ExceptionTypeService;
import com.motong.gongdan.service.UserService;
import com.motong.gongdan.util.LoginUtil;
import com.motong.gongdan.vo.ExcelModel.ExceptionGetListExcelModel;
import com.motong.gongdan.vo.system.common.query.IdValueQuery;
import com.motong.gongdan.vo.system.exceptionHandle.query.ExceptionGetListQuery;
import com.motong.gongdan.vo.system.exceptionHandle.query.ExceptionGetTypeListQuery;
import com.motong.gongdan.vo.system.exceptionHandle.query.TimeoutReportQuery;
import com.motong.gongdan.vo.system.exceptionHandle.vo.ExceptionGetListVo;
import com.motong.gongdan.vo.system.exceptionHandle.vo.ExceptionGetNoticeListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "异常设置")
@RestController
@RequestMapping("/sys/dealException")
public class ExceptionHandleController {

    @Resource
    private UserService userService;

    @Resource
    private ExceptionInfoService exceptionInfoService;

    @Resource
    private ExceptionTypeService exceptionTypeService;

    @Resource
    private ExceptionNoticeService exceptionNoticeService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @ApiOperation("获取异常报表")
    @PostMapping("/getList")
    @UserLoginToken
    public ResponseData<List<ExceptionGetListVo>> getList(@RequestBody(required = false) ExceptionGetListQuery query) {
        query = Optional.ofNullable(query).orElse(new ExceptionGetListQuery());
        Page<ExceptionGetListVo> data = exceptionInfoService.getList(new Page<>(query.getPage(), query.getLimit()), query);
        return ResponseData.success(data.getRecords(), data.getTotal());
    }


    @ApiOperation("获取异常类型列表")
    @PostMapping("/getTypeList")
    @UserLoginToken
    public ResponseData<List<ExceptionType>> getTypeList(@RequestBody(required = false) ExceptionGetTypeListQuery query) {
        query = Optional.ofNullable(query).orElse(new ExceptionGetTypeListQuery());
        List<ExceptionType> data = exceptionTypeService.getList(query);
        return ResponseData.success(data);
    }


    @ApiOperation("添加异常类型信息")
    @PostMapping("/typeEdit")
    @UserLoginToken
    public ResponseData<String> typeEdit(@RequestBody ExceptionType query) {
        boolean isUpdate = Objects.nonNull(query.getId());
        query.setUpdateUser(LoginUtil.getLoginUserId()).setUpdateTime(new Date());
        if (!isUpdate) {
            query.setCreateUser(LoginUtil.getLoginUserId()).setCreateTime(new Date());
        }
        exceptionTypeService.saveOrUpdate(query);
        return ResponseData.success(String.format("%s成功!", isUpdate ? "编辑" : "添加"));
    }

    @ApiOperation("删除异常类型信息")
    @PostMapping("/typeDel")
    @UserLoginToken
    public ResponseData<String> typeDel(@RequestBody IdValueQuery query) {
        if (StringUtils.hasLength(query.getIds())) {
            exceptionTypeService.removeByIds(query.getIdList());
        }
        return ResponseData.success("删除成功!");
    }

    @ApiOperation("获取通知列表")
    @PostMapping("/getNoticeList")
    @UserLoginToken
    public ResponseData<List<ExceptionGetNoticeListVo>> getNoticeList(@RequestBody(required = false) ExceptionGetTypeListQuery query) {
        LambdaQueryWrapper<ExceptionNotice> noticeQW = new LambdaQueryWrapper<ExceptionNotice>()
                .eq(Objects.nonNull(query.getGroupId()), ExceptionNotice::getGroupId, query.getGroupId())
                .eq(Objects.nonNull(query.getLampColor()), ExceptionNotice::getLampColor, query.getLampColor());
        List<ExceptionNotice> tempData = exceptionNoticeService.list(noticeQW);
        List<ExceptionGetNoticeListVo> data = tempData.stream().map(i -> new ExceptionGetNoticeListVo().setId(i.getId()).setDelayTime(i.getDelayTime())
                .setInfoType(i.getInfoType()).setInfoUserId(i.getInfoUserId()).setInfoUserName(i.getInfoUserName())).collect(Collectors.toList());
        return ResponseData.success(data);
    }

    @ApiOperation("编辑通知列表")
    @PostMapping("/editNotice")
    @UserLoginToken
    public ResponseData<String> editNotice(@RequestBody ExceptionNotice query) {
        boolean isUpdate = Objects.nonNull(query.getId());
        query.setUpdateUser(LoginUtil.getLoginUserId()).setUpdateTime(new Date());
        if (!isUpdate) {
            query.setCreateUser(LoginUtil.getLoginUserId()).setCreateTime(new Date());
        }
        query.setInfoUserName("");
        if (Objects.nonNull(query.getInfoUserId())) {
            List<String> userIds = Arrays.asList(Optional.ofNullable(query.getInfoUserId()).orElse("").split(","));
            if (!CollectionUtils.isEmpty(userIds)) {
                String userNames = userService.listByIds(userIds).stream().map(User::getName).collect(Collectors.joining(","));
                query.setInfoUserName(userNames);
            }
        }
        exceptionNoticeService.saveOrUpdate(query);
        return ResponseData.success(String.format("%s成功!", isUpdate ? "编辑" : "添加"));
    }


    @ApiOperation("删除异常通知信息")
    @PostMapping("/delNotice")
    @UserLoginToken
    public ResponseData<String> delNotice(@RequestBody IdValueQuery query) {
        if (StringUtils.hasLength(query.getIds())) {
            exceptionNoticeService.removeByIds(query.getIdList());
        }
        return ResponseData.success("删除成功!");
    }

    @ApiOperation("黄灯/红灯超时异常上报")
    @PostMapping("/setTimeoutReport")
    @UserLoginToken
    public ResponseData<String> setTimeoutReport(@RequestBody TimeoutReportQuery query) {
        redisTemplate.opsForHash().put(CommonConstant.EXCEPTION_TIMEOUT_HASH_KEY,
                query.getLampColor().toString().concat(":").concat(LoginUtil.getLoginUserFactory().toString()),
                query.getMinute());
        return ResponseData.success("设置成功!");
    }

    @ApiOperation("获取超时异常上报时间")
    @PostMapping("/getTimeoutReport")
    @UserLoginToken
    public ResponseData<Long> getTimeoutReport(@RequestBody TimeoutReportQuery query) {
        Object minute = redisTemplate.opsForHash().get(CommonConstant.EXCEPTION_TIMEOUT_HASH_KEY,
                query.getLampColor().toString().concat(":").concat(LoginUtil.getLoginUserFactory().toString()));
        if (Objects.nonNull(minute)) {
            query.setMinute(Convert.toLong(minute));
        }
        return ResponseData.success(query.getMinute());
    }

    @UserLoginToken
    @PostMapping("/export")
    @ApiOperation(value = "导出异常报表")
    public void outExceptionReportExcel(@RequestBody(required = false) ExceptionGetListQuery query, HttpServletResponse response) {
        List<ExceptionGetListVo> data = this.getList(query).getData();
        if (!CollectionUtils.isEmpty(data)) {
            try {
                List<ExceptionGetListExcelModel> exportData = data.stream().map(i -> {
                    ExceptionGetListExcelModel exceptionGetListExcelModel = new ExceptionGetListExcelModel();
                    BeanUtil.copyProperties(i, exceptionGetListExcelModel);
                    return exceptionGetListExcelModel;
                }).collect(Collectors.toList());
                String fileName = "异常报表" + System.currentTimeMillis() + ".xlsx";
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                EasyExcel.write(response.getOutputStream()).registerWriteHandler(new CustomCellWriteHandler()).sheet("异常报表导出数据").head(ExceptionGetListExcelModel.class).doWrite(exportData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
